//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2007 CORE Solutions Limited
// All rights reserved.
// PROPRIETARY AND CONFIDENTIAL INFORMATION.
// Use is subject to license terms.
//
// FUNCTION ID      :   CATALOG_DTL_TEMPLATE
// AUTHOR           :   Craig Chun
// DATE CREATE      :   2007/07/20
// DESCRIPTION      :   a ACTION file for the function, CATALOG_DTL_TEMPLATE
//                  :
//                  :
//                  :
//
// MODIFICATION HISTORY:
// DATE         AUTHOR          VERSION NO.         COMMENT
// -----------  --------------  ------------------  -------------------
// 2007/07/20   Craig Chun      1.0                 source is generated.
//
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package com.erp.app.setup.itemDetailTemplate.web;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.erp.app.common.ProjectConstants;
import com.erp.app.setup.itemDetailTemplate.criteria.CatalogDtlTemplateSrchCriteria;
import com.erp.app.setup.itemDetailTemplate.vo.CatalogDtlTemplateVo;
import com.erp.app.util.web.WebUtil;
import com.erp.common.web.SearchResultRow;
import com.erp.framework.util.BeanUtil;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.model.pk.SimpleBasePk;
import com.erp.framework.model.schema.TableSchema;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;
import com.erp.framework.util.user.UserDelegate;
import com.erp.framework.controller.action.SimplePageEditStyleActionTemplate;

/**
* A <strong>Page Edit Action</strong> is an adapter between the contents of an incoming
* HTTP request and the corresponding business logic that should be executed to
* process this request.  The controller (ActionServlet) will select an
* appropriate Action for each request.
* The main purpose for this action class is to handle the one-page document events
* from the web browsers.
*
* @author          Craig Chun
* @version 1.0     2007/07/20
* @since           FrameWork 1.0
*
*/
public class CatalogDtlTemplateAction extends SimplePageEditStyleActionTemplate {

	////////////////////////////////////////////////////////////////////////////////
	// CONSTANTS DEFINITION
	////////////////////////////////////////////////////////////////////////////////
	public static final String ACTION_BACK = "back";
	public static final String ACTION_ADD_DTL_ROW = "addDtlRow";
	public static final String STATUS_ADD_DTL_ROW = "addDtlRow";

	////////////////////////////////////////////////////////////////////////////////
	// GLOBAL VARIABLES DEFINITION
	////////////////////////////////////////////////////////////////////////////////



	////////////////////////////////////////////////////////////////////////////////
	// LOGICAL AND BUSINESS METHODS
	////////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////////
	// END OF LOGICAL AND BUSINESS METHODS
	////////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////////
	// OVERRIDES PARENT'S OPTIONAL METHODS
	////////////////////////////////////////////////////////////////////////////////

	//the following method is only to be overwritten by sub-class if intended
	//to set the aut-search on-load to on/off
	protected boolean getLoadOnEnter() {

		//auto-search when load
		return true;
	}

	//the following method is only to be overwritten by sub-class if intended
	//to set the clearing search result sets on-load to on/off
	protected boolean getResetOnEnter() {

		//reset last searched results when load
		return true;
	}


		//TODO: Add the following line to ProjectSecurityConstants.java
		//public static final String SP_SHARE_CATALOG_DTL_TEMPLATE = "SP_SHARE_CATALOG_DTL_TEMPLATE";
	protected void afterAddRow(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CatalogDtlTemplateForm form = (CatalogDtlTemplateForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			ArrayList rows = form.getMultiRows();
			if (rows != null && rows.size() > 0) {
				CatalogDtlTemplateRow row = (CatalogDtlTemplateRow) rows.get(rows.size() - 1);
				row.setCompanyCode(WebUtil.getAppropriateCompanyCode(session, ProjectConstants.SP_SHARE_CATALOG_DTL_TEMPLATE));
			}
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected String getSimpleSrchMenuId() {

		//TODO: Add the following line to ProjectMenuConstants.java

		return ProjectConstants.MOD_CATALOG_DTL_TEMPLATE;
	}

	////////////////////////////////////////////////////////////////////////////////
	// END OF OPTIONAL METHODS
	////////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////////
	// IMPLEMENTS PARENT'S ABSTRACT METHODS
	////////////////////////////////////////////////////////////////////////////////

	protected String getModuleName(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request,HttpServletResponse response) {

		//TODO: Add the following line to ProjectMenuConstants.java
		//public static final String MOD_CATALOG_DTL_TEMPLATE = "MOD_CATALOG_DTL_TEMPLATE";
		return ProjectConstants.MOD_CATALOG_DTL_TEMPLATE;
	}

	protected String getFunctionId() {

		//struts-config xxxxx.do
		return "catalogDtlTemplate.do";
	}

	protected void setFormType(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
		 HttpServletResponse response, ActionErrors errors) {

		CatalogDtlTemplateForm form = (CatalogDtlTemplateForm) formIn;
		form.setFormType(ProjectConstants.FORM_TYPE_PAGE_EDIT);
	}

	protected String getMasterDelegateName() {

		//the corresponding delegate session name
		return "catalogDtlTemplateDelegate";
	}

	protected Class getMasterFormClass() {

		//the corresponding form class
		return CatalogDtlTemplateForm.class;
	}

	protected Class getMasterVOClass() {

		//corresponding master vo class
		return CatalogDtlTemplateVo.class;
	}

	protected Class getDetailVOClass() {

		//corresponding detail vo class
		return CatalogDtlTemplateVo.class;
	}

	protected Class getDetailFormClass() {
		//corresponding detail row class
		return CatalogDtlTemplateRow.class;
	}

	protected String getDetailFormSessionName() {

		//corresponding detail form session name
		return "catalogDtlTemplateForm";
	}

	protected Class getSearchCriteriaClass() {

		//corresponding searching criteria class
		return CatalogDtlTemplateSrchCriteria.class;
	}

	protected void setOtherCriteria(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response,
		ActionErrors errors, Object criteria) {

		HttpSession session = request.getSession(false);
		User user = (User) session.getAttribute(ProjectConstants.SESSION_USER);
		CatalogDtlTemplateSrchCriteria crit = (CatalogDtlTemplateSrchCriteria) criteria;
		CatalogDtlTemplateForm form = (CatalogDtlTemplateForm) formIn;
		//TODO: Add the following line to ProjectSecurityConstants.java

		String companyCode = WebUtil.getAppropriateCompanyCode(session, ProjectConstants.SP_SHARE_CATALOG_DTL_TEMPLATE);
		if(session.getAttribute(ProjectConstants.SESSION_EDIT_ITEM_DETAIL_TEMPLATE_CRITERIA) != null){
			CatalogDtlTemplateSrchCriteria sessionCrit =(CatalogDtlTemplateSrchCriteria) session.getAttribute(ProjectConstants.SESSION_EDIT_ITEM_DETAIL_TEMPLATE_CRITERIA);
			crit.setSrchNodeIdFr(sessionCrit.getSrchNodeIdFr());
			form.setSrchNodeIdFr(sessionCrit.getSrchNodeIdFr());
		}
		crit.setSrchCompanyCode(companyCode);
		crit.setSearchResult(true);
	}

	////////////////////////////////////////////////////////////////////////////////
	// END OF ABSTRACT METHODS
	////////////////////////////////////////////////////////////////////////////////
	public ActionForward processActionBack(ActionMapping mapping, ActionForm formIn,
			HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = new ActionForward(mapping.getInput());
		actionForward = mapping.findForward(ACTION_BACK);
		return actionForward;
	}

	public ActionForward processActionAddDtlRow(ActionMapping mapping, ActionForm formIn,
			HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
		ActionForward actionForward = new ActionForward(mapping.getInput());
		CatalogDtlTemplateForm form = (CatalogDtlTemplateForm) formIn;
		HttpSession session = request.getSession(false);
        try{

        	 LinkedList criteriaList = new LinkedList();
             String wh = "";
             wh = "COMPANY_CODE='"
                     + WebUtil.getAppropriateCompanyCode(session, null)
                     + "'";
             wh += " AND REF_MASTER_CODE='" + ProjectConstants.CD_CATALOG_DTL_TYPE+ "'";

             TableSchema ts = form.getTs();

             criteriaList.add(ts.getDisplayWebLabelByObjectId("LBL_SRCH_ITEM_DETAIL_TYPE"));
             criteriaList.add("COMBO");
             criteriaList.add("");
             criteriaList.add("t_code_dtl");
             criteriaList.add("REF_CODE");
             criteriaList.add("REF_DESC");
             criteriaList.add(wh);
             criteriaList.add("SEQ, REF_DESC");
             criteriaList.add("");

             criteriaList.add(ts.getDisplayWebLabelByObjectId("LBL_SRCH_ITEM_DETAIL_NAME"));
             criteriaList.add("INPUT_WITH_WILDCARD");
             criteriaList.add("");

             ArrayList criteriaColumnList = new ArrayList();
             criteriaColumnList.add("A.DTL_TYPE");
             criteriaColumnList.add("b.ref_desc");

             ArrayList rsltTextList = new ArrayList();
             ArrayList rsltColumnList = new ArrayList();
             Hashtable tblParams = new Hashtable();

             rsltTextList.add(ts.getDisplayWebLabelByObjectId("LBL_SRCH_ITEM_DETAIL_TYPE"));
             rsltTextList.add(ts.getDisplayWebLabelByObjectId("LBL_SRCH_ITEM_DETAIL_NAME"));



             rsltColumnList.add("b.ref_desc");
             rsltColumnList.add("A.DTL_NAME");
             rsltColumnList.add("A.UOM");
             rsltColumnList.add("A.COMPANY_CODE");
             rsltColumnList.add("A.DTL_ID");
             rsltColumnList.add("A.DTL_TYPE");
             rsltColumnList.add("A.OPTION_CODE");



             String where = "b.COMPANY_CODE='" + WebUtil.getAppropriateCompanyCode(session, null)
             + "' AND A.DTL_TYPE = B.REF_CODE AND B.REF_MASTER_CODE = '" + ProjectConstants.CD_CATALOG_DTL_TYPE + "' " +
             " and a.STATUS = '" + ProjectConstants.GENERIC_ACTIVE + "' " ;

             tblParams.put(ProjectConstants.SESSION_TABLE, " T_catalog_dtl A, T_CODE_DTL b ");
             tblParams.put(ProjectConstants.SESSION_WHERE, where);

             HashMap params = new HashMap();
             params.put(ProjectConstants.SESSION_SESSION_NAME, getSessionSimpleMastersStatus());
             params.put(ProjectConstants.SESSION_SESSION_VALUE, STATUS_ADD_DTL_ROW);
             params.put(ProjectConstants.SESSION_OPENER_PATH, getFunctionId());
             params.put(ProjectConstants.SESSION_EVENTSRC, form.getPageEventSrc());
             params.put(ProjectConstants.SESSION_CRITERIA_LIST, criteriaList);
             params.put(ProjectConstants.SESSION_CRITERIA_COLUMN_LIST, criteriaColumnList);
             params.put(ProjectConstants.SESSION_RESULT_TEXT_LIST, rsltTextList);
             params.put(ProjectConstants.SESSION_RESULT_COLUMN_LIST, rsltColumnList);
             params.put(ProjectConstants.SESSION_TABLE_PARAMS, tblParams);
             session.setAttribute(ProjectConstants.SESSION_COMMON_SEARCH_PARAMETERS, params);

        }catch (Exception e) {
            Logger.logExceptions(this, e);
        }

		return actionForward;
	}

	public ActionForward processStatusAddDtlRow(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response, ActionErrors errors, String rb_status) {
		ActionForward actionForward = new ActionForward(mapping.getInput());
		CatalogDtlTemplateForm form = (CatalogDtlTemplateForm) formIn;
		HttpSession session = request.getSession(false);
		HashMap params = (HashMap) session.getAttribute(ProjectConstants.SESSION_COMMON_SEARCH_PARAMETERS);
        session.removeAttribute(ProjectConstants.SESSION_COMMON_SEARCH_PARAMETERS);
        ArrayList selectedList = (ArrayList) params.get(ProjectConstants.SESSION_SELECTED_LIST);
        if (selectedList == null || selectedList.size() == 0)
            return actionForward;
    	HashMap itemDetailMap = new HashMap();
    	ArrayList detailRows = form.getMultiRows();
    	for(int i = 0; i < detailRows.size(); i++){
    		CatalogDtlTemplateRow row = (CatalogDtlTemplateRow) detailRows.get(i);
    		if(!CommonUtil.isEmpty(row.getIsDelete()))
    			continue;
    		itemDetailMap.put(row.getDtlId(), row.getDtlId());
    	}
    	String notAddDetailList = "";
    	try{
    		for (int i = 0; i < selectedList.size(); i++) {
    			SearchResultRow sRow = (SearchResultRow) selectedList.get(i);

                if (sRow == null)
                    continue;


                ArrayList dtlRows = form.getMultiRows();

                int largestId = -1;

                try {
                    largestId = Integer.parseInt(CommonUtil.getNextSequence(dtlRows, "dtlId"));
                } catch (InvocationTargetException e) {
                    largestId = 1;
                } catch (NoSuchMethodException e) {
                    largestId = 1;
                } catch (IllegalAccessException e) {
                    largestId = 1;
                }

                int largestSeqId = -1;

                try {
                	largestSeqId = Integer.parseInt(CommonUtil.getNextSequence(dtlRows, "hdrSeq"));
                } catch (InvocationTargetException e) {
                	largestSeqId = 1;
                } catch (NoSuchMethodException e) {
                	largestSeqId = 1;
                } catch (IllegalAccessException e) {
                	largestSeqId = 1;
                }
                if(CommonUtil.isEmpty(itemDetailMap.get(CommonUtil.nullToString((String)sRow.getColumn5())))){
                	CatalogDtlTemplateRow rowToAdd = new CatalogDtlTemplateRow();
                	if(session.getAttribute(ProjectConstants.SESSION_EDIT_ITEM_DETAIL_TEMPLATE_CRITERIA) != null){
            			CatalogDtlTemplateSrchCriteria sessionCrit =(CatalogDtlTemplateSrchCriteria) session.getAttribute(ProjectConstants.SESSION_EDIT_ITEM_DETAIL_TEMPLATE_CRITERIA);
            			rowToAdd.setNodeId(sessionCrit.getSrchNodeIdFr());
            		}
                	rowToAdd.setCompanyCode(sRow.getColumn4());
                	rowToAdd.setDtlId(CommonUtil.nullToString((String)sRow.getColumn5()));
                	rowToAdd.setHdrSeq(String.valueOf(largestSeqId));
                	rowToAdd.setHdrStatus(ProjectConstants.GENERIC_ACTIVE);
                	rowToAdd.setItemDetailName(CommonUtil.nullToString((String)sRow.getColumn2()));
                	rowToAdd.setItemDetailType(CommonUtil.nullToString((String)sRow.getColumn1()));
                	rowToAdd.setHdrBrowserColumn("");
                	form.addRow(rowToAdd);
                }else {
                	if(CommonUtil.isEmpty(notAddDetailList)){
                		notAddDetailList = CommonUtil.nullToString((String)sRow.getColumn2());
                	}else{
                		notAddDetailList = notAddDetailList + ", " +  CommonUtil.nullToString((String)sRow.getColumn2());
                	}
                }

    		}
    		if(!CommonUtil.isEmpty(notAddDetailList)){
	        	session.setAttribute(ProjectConstants.SESSION_ALERT_AFTER_ADD_ITEM_DETAIL, ProjectConstants.GENERIC_YES);
	        	session.setAttribute(ProjectConstants.SESSION_CATEGORY_DETAIL_ALREADY_EXISTS_ITEMS, notAddDetailList);
    	    }

    	}catch (Exception e) {
            Logger.logExceptions(this, e);
        }
		return actionForward;
	}




}
